import { useCallback } from "react";
import { useProject } from "server";
import { useUrlQueryParam } from "./useUrlQueryParam";

export const useProjectModal = () => {
  const [
    { projectCreate, projectId },
    setProjectModalVisible,
  ] = useUrlQueryParam(["projectCreate", "projectId"]);
  const { data: editingProject, isLoading } = useProject(Number(projectId));

  const open = useCallback(() => {
    setProjectModalVisible({ projectCreate: true });
  }, [setProjectModalVisible]);

  const close = useCallback(() => {
    setProjectModalVisible({ projectCreate: undefined, projectId: undefined });
  }, [setProjectModalVisible]);

  const edit = useCallback(
    (id: number) => {
      setProjectModalVisible({ projectCreate: true, projectId: id });
    },
    [setProjectModalVisible]
  );

  return {
    visible: projectCreate === "true",
    open,
    close,
    edit,
    editingProject,
    isLoading,
  };
};
